package com.yxc.live_it.activity;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewConfiguration;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.ViewPager;

import com.yxc.live_it.R;
import com.yxc.live_it.fragement.FindFragment;
import com.yxc.live_it.fragement.LiveFragment;
import com.yxc.live_it.fragement.MessFragment;
import com.yxc.live_it.fragement.RecordFragment;
import com.yxc.live_it.fragement.SelfFragment;

import java.lang.reflect.Method;

public class MainActivity extends FragmentActivity implements OnClickListener{

    private long lastTime;//退出键的最后时间
    private ViewPager mViewPager;// 用来放置界面切换
    // 三个Tab，每个Tab包含一个按钮
    private LinearLayout mTabRecord;
    private LinearLayout mTabFind;
    private LinearLayout mTabLive;
    private LinearLayout mTabMess;
    private LinearLayout mTabSelf;
    // 5个按钮
    private ImageButton mRecordImg;
    private ImageButton mFindImg;
    private ImageButton mLiveImg;
    private ImageButton mMessImg;
    private ImageButton mSelfImg;
    // 初始化5个Fragment
    private Fragment record;
    private Fragment find;
    private Fragment live;
    private Fragment mess;
    private Fragment self;

    //初始化底部5个文本
    private TextView recordTxt;
    private TextView findTxt;
    private TextView liveTxt;
    private TextView messTxt;
    private TextView selfTxt;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        initView();
        initEvent();
        initViewPage(0);

        mTabRecord.performClick();
        //隐藏虚拟导航栏
        if(hasNavBar(this)){
            hideBottomUIMenu();
        }

    }

    /*
     * 判断哪个要显示，及设置按钮图片
     */
    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
            case R.id.id_tab_record:
                initViewPage(0);
                mViewPager.setCurrentItem(0);
                resetImg();
                mRecordImg.setImageResource(R.mipmap.index_record_activity);
                recordTxt.setTextColor(this.getResources().getColor(R.color.txt_activity));
                break;
            case R.id.id_tab_find:
                initViewPage(1);
                mViewPager.setCurrentItem(1);
                resetImg();
                mFindImg.setImageResource(R.mipmap.index_find_activity);
                findTxt.setTextColor(this.getResources().getColor(R.color.txt_activity));
                break;
            case R.id.id_tab_live:
                initViewPage(2);
                mViewPager.setCurrentItem(2);
                resetImg();
                mLiveImg.setImageResource(R.mipmap.index_live_activity);
                liveTxt.setTextColor(this.getResources().getColor(R.color.txt_activity));
                break;
            case R.id.id_tab_mess:
                initViewPage(3);
                mViewPager.setCurrentItem(3);
                resetImg();
                mMessImg.setImageResource(R.mipmap.index_mess_activity);
                messTxt.setTextColor(this.getResources().getColor(R.color.txt_activity));
                break;
            case R.id.id_tab_self:
                initViewPage(4);
                mViewPager.setCurrentItem(4);
                resetImg();
                mSelfImg.setImageResource(R.mipmap.index_self_activity);
                selfTxt.setTextColor(this.getResources().getColor(R.color.txt_activity));
                break;
            default:
                break;
        }
    }

    /*
     * 初始化配置
     */
    private void initView() {
        mViewPager = findViewById(R.id.id_viewpage);
        // 初始化5个LinearLayout
        mTabRecord = findViewById(R.id.id_tab_record);
        mTabFind = findViewById(R.id.id_tab_find);
        mTabLive = findViewById(R.id.id_tab_live);
        mTabMess = findViewById(R.id.id_tab_mess);
        mTabSelf = findViewById(R.id.id_tab_self);
        // 初始化5个按钮
        mRecordImg = findViewById(R.id.id_tab_record_img);
        mFindImg = findViewById(R.id.id_tab_find_img);
        mLiveImg = findViewById(R.id.id_tab_live_img);
        mMessImg = findViewById(R.id.id_tab_mess_img);
        mSelfImg = findViewById(R.id.id_tab_self_img);

        //初始化底部5个文本
        recordTxt = findViewById(R.id.record_txt);
        findTxt = findViewById(R.id.find_txt);
        liveTxt = findViewById(R.id.live_txt);
        messTxt = findViewById(R.id.mess_txt);
        selfTxt = findViewById(R.id.self_txt);
    }

    /*
     * 初始化initViewPage
     */
    private void initViewPage(int i) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();// 创建一个事务
        hideFragment(transaction);// 我们先把所有的Fragment隐藏了，然后下面再开始处理具体要显示的Fragment
        switch (i) {
            case 0:
                if (record == null) {
                    record = new RecordFragment();
                    transaction.add(R.id.id_content, record);// 将微信聊天界面的Fragment添加到Activity中
                } else {
                    transaction.show(record);
                }
                break;
            case 1:
                if (find == null) {
                    find = new FindFragment();
                    transaction.add(R.id.id_content, find);
                } else {
                    transaction.show(find);
                }
                break;
            case 2:
                if (live == null) {
                    live = new LiveFragment();
                    transaction.add(R.id.id_content, live);
                } else {
                    transaction.show(live);
                }
                break;
            case 3:
                if (mess == null) {
                    mess = new MessFragment();
                    transaction.add(R.id.id_content, mess);
                } else {
                    transaction.show(mess);
                }
                break;
            case 4:
                if (self == null) {
                    self = new SelfFragment();
                    transaction.add(R.id.id_content, self);
                } else {
                    transaction.show(self);
                }
                break;
            default:
                break;
        }

        transaction.commit();// 提交事务
    }

    private void initEvent() {
        mTabRecord.setOnClickListener(this);
        mTabFind.setOnClickListener(this);
        mTabLive.setOnClickListener(this);
        mTabMess.setOnClickListener(this);
        mTabSelf.setOnClickListener(this);
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int arg0) {
                int currentItem = mViewPager.getCurrentItem();
                switch (currentItem) {
                    case 0:
                        resetImg();
                        mRecordImg.setImageResource(R.mipmap.index_record_activity);
                        recordTxt.setTextColor(Color.parseColor("#F47936"));
                        break;
                    case 1:
                        resetImg();
                        mFindImg.setImageResource(R.mipmap.index_find_activity);
                        findTxt.setTextColor(Color.parseColor("#F47936"));
                        break;
                    case 2:
                        resetImg();
                        mLiveImg.setImageResource(R.mipmap.index_live_activity);
                        liveTxt.setTextColor(Color.parseColor("#F47936"));
                    case 3:
                        resetImg();
                        mMessImg.setImageResource(R.mipmap.index_mess_activity);
                        messTxt.setTextColor(Color.parseColor("#F47936"));
                    case 4:
                        resetImg();
                        mSelfImg.setImageResource(R.mipmap.index_self_activity);
                        selfTxt.setTextColor(Color.parseColor("#F47936"));
                    default:
                        break;
                }
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });
    }

    /*
     * 隐藏所有的Fragment
     */
    private void hideFragment(FragmentTransaction transaction) {
        if (record != null) {
            transaction.hide(record);
        }
        if (find != null) {
            transaction.hide(find);
        }
        if (live != null) {
            transaction.hide(live);
        }
        if (mess != null) {
            transaction.hide(mess);
        }
        if (self != null) {
            transaction.hide(self);
        }
    }

    /*
     * 把所有图片变暗
     */
    private void resetImg() {
        mRecordImg.setImageResource(R.mipmap.index_record);
        mFindImg.setImageResource(R.mipmap.index_find);
        mLiveImg.setImageResource(R.mipmap.index_live);
        mMessImg.setImageResource(R.mipmap.index_mess);
        mSelfImg.setImageResource(R.mipmap.index_self);

        recordTxt.setTextColor(this.getResources().getColor(R.color.txt_no_activity));
        findTxt.setTextColor(this.getResources().getColor(R.color.txt_no_activity));
        liveTxt.setTextColor(this.getResources().getColor(R.color.txt_no_activity));
        messTxt.setTextColor(this.getResources().getColor(R.color.txt_no_activity));
        selfTxt.setTextColor(this.getResources().getColor(R.color.txt_no_activity));
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu(){
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
//                    | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                    | View.SYSTEM_UI_FLAG_IMMERSIVE;
            decorView.setSystemUiVisibility(uiOptions);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }
    /**
     * 检查是否存在虚拟按键栏
     * @param context
     * @return
     */
    public static boolean hasNavBar(Context context) {
        Resources res = context.getResources();
        int resourceId = res.getIdentifier("config_showNavigationBar", "bool", "android");
        if (resourceId != 0) {
            boolean hasNav = res.getBoolean(resourceId);
            // check override flag
            String sNavBarOverride = getNavBarOverride();
            if ("1".equals(sNavBarOverride)) {
                hasNav = false;
            } else if ("0".equals(sNavBarOverride)) {
                hasNav = true;
            }
            return hasNav;
        } else { // fallback
            return !ViewConfiguration.get(context).hasPermanentMenuKey();
        }
    }

    /**
     * 判断虚拟按键栏是否重写
     * @return
     */
    private static String getNavBarOverride() {
        String sNavBarOverride = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            try {
                Class c = Class.forName("android.os.SystemProperties");
                Method m = c.getDeclaredMethod("get", String.class);
                m.setAccessible(true);
                sNavBarOverride = (String) m.invoke(null, "qemu.hw.mainkeys");
            } catch (Throwable e) {
            }
        }
        return sNavBarOverride;
    }



    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - lastTime <= 2000) {
                finish();
            } else {
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                lastTime = System.currentTimeMillis();
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}
